// goods/pages/order/order.js
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
let login = require('../../../common/script/login');
let wxParse = require('../../wxParse/wxParse.js');
const utils = require('../../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navData: [{
        name: '全部订单',
        type: ''
      },
      {
        name: '待付款',
        type: 'WAITPAY'
      },
      {
        name: '待发货',
        type: 'WAITSEND'
      },
      {
        name: '待收货',
        type: 'WAITRECEIVE'
      },
      {
        name: '已完成',
        type: 'FINISH'
      }
    ],
    reasons: [
      '订单不能按预计时间送达',
      '操作有误（商品、地址等选错）',
      '重复下单/误下单',
      '其他渠道价格更低',
      '该商品降价了',
      '不想买了'
    ],
    navIndex: 0,
    page: 1,
    listData: [],
    isEnd: true,
    isWithout: true,
    showModal: false,
    concent_list: ['微信支付', '会员卡支付'],
    curIndex: 0,
    money: '',
    sn: ''
  },
  //点击列表按钮
  navClick(e) {
    const that = this;
    that.setData({
      navIndex: e.currentTarget.dataset.index,
      page: 1,
      isEnd: true,
      isWithout: true,
    })
    that.getData();
  },
  //客服
  popSelect(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.tel //仅为示例，并非真实的电话号码
    })
  },
  // 订单详情
  toOrderDetails(e) {
    const that = this;
    let sn = e.currentTarget.dataset.sn;
    let id = e.currentTarget.dataset.id;
    let storeid = e.currentTarget.dataset.storeid;
    wx.navigateTo({
      url: `/goods/pages/orderDetails/orderDetails?sn=${sn}&id=${id}&store_id=${storeid}`,
    })
  },
  getData() {
    const that = this;
    let data = {
      token: wx.getStorageSync('token'),
      type: that.data.navData[that.data.navIndex].type,
      p: that.data.page
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getOrderList, data).then(res => {
      wx.hideLoading();
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
      if (res.data.status == 1) {
        if (res.data.result == null || res.data.result.length == 0) {
          console.log(111111)
          that.setData({
            isWithout: false,
            listData: []
          })
        } else {
          that.setData({
            isWithout: true,
            listData: res.data.result
          })
          wx.pageScrollTo({
            scrollTop: 0
          })
        }
      }
    })
  },
  //确认收货
  orderConfirm(e) {
    const that = this;
    let order_id = e.currentTarget.dataset.order_id;
    let data = {
      token: wx.getStorageSync('token'),
      order_id: order_id
    }
    wx.showModal({
      content: '是否确认收货',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(e) {
        if (e.confirm) {
          wx.showLoading({
            title: '加载中...',
          })
          myRequest.EasyHttp.post(api.reqUrls.orderConfirm, data).then(res => {
            wx.hideLoading();
            if (res.data.status == 1) {
              wx.showToast({
                title: res.data.msg,
                icon: 'success',
                duration: 2000,
              })
              setTimeout(() => {
                that.getData();
              }, 2000)
            } else {
              wx.showModal({
                content: res.data.msg,
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {

                  }
                }
              })
            }
          })
        }
      }
    })
  },
  // 查看物流
  toLogistics(e) {
    let order_id = e.currentTarget.dataset.order_id;
    wx.navigateTo({
      url: `/goods/pages/logistics/logistics?order_id=${order_id}`,
    })
  },
  // 去申请售后
  toAfterSale(e) {
    let order_id = e.currentTarget.dataset.order_id;
    wx.navigateTo({
      url: `/goods/pages/afterSales/afterSales?order_id=${order_id}&type=1`
    })
  },
  // 隐藏模态对话框
  hideModal() {
    const that = this;
    that.setData({
      showModal: false
    });
  },
  // 显示模态对话框
  showModel(e) {
    const that = this;
    let money = e.currentTarget.dataset.money;
    let sn = e.currentTarget.dataset.sn;
    let memberData = wx.getStorageSync('memberData')
    if (memberData) {
      that.setData({
        curIndex: 0,
        showModal: true,
        money,
        sn
      });
    } else {
      that.setData({
        money,
        sn
      });
      that.debounces()
    }
  },
  // 选择模态框
  choose(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      curIndex: index
    })
  },
  debounces: utils.throttle(function () {
    this.setData({
      showModal: false
    });
    this.onConfirm()
  }, 5000),
  onConfirm(e) {
    const that = this
    let amountData = {
      token: wx.getStorageSync('token'),
      trade_type: "JSAPI",
      master_order_sn: that.data.sn,
      account: that.data.money
    }
    wx.showLoading({
      title: '加载中...',
    })
    // curIndex==0 是微信支付，curIndex==1是会员卡支付
    let curIndex = that.data.curIndex
    if (curIndex == 0) {
      myRequest.EasyHttp.post(api.reqUrls.doPay, amountData).then(prop => {
        wx.hideLoading();
        if (prop.data.status == 1) {
          wx.requestPayment({ // 调取支付
            timeStamp: prop.data.result.timeStamp.toString(),
            nonceStr: prop.data.result.nonceStr,
            package: prop.data.result.package,
            signType: prop.data.result.signType,
            paySign: prop.data.result.sign,
            success(res) {
              if (res.errMsg == "requestPayment:ok") {
                console.log(111)
                wx.showToast({
                  title: '付款成功',
                  icon: 'success',
                  duration: 2000
                })
                wx.navigateTo({
                  url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${that.data.sn}&type=2`
                })
              } else {
                console.log(222)
                wx.showModal({
                  content: '付款失败',
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {
                    if (e.confirm) {

                    }
                  }
                })
              }
            },
            fail(res) {
              wx.showModal({
                content: '付款失败',
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {
                    console.log(333)

                  }
                }
              })
            }
          })
        }
      })
    } else {
      myRequest.EasyHttp.post(api.reqUrls.cardDoPay, amountData).then(prop => {
        wx.hideLoading();
        if (prop.data.status == 1) {
          wx.showToast({
            title: "付款成功",
            icon: 'success',
            duration: 2000
          })

          wx.navigateTo({
            url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${that.data.sn}&type=2`
          })
        } else if (prop.data.status == -1002) {
          // wx.showModal({
          //   content: '会员卡余额不足，是否去充值？',
          //   confirmText: '去充值',
          //   success(e) {
          //     if (e.confirm) {
          //       wx.navigateTo({
          //         url: `/package/pages/recharge/recharge`,
          //       })
          //     }
          //   }
          // })
          wx.showModal({
            content: prop.data.msg,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff5151',
            success(e) {
              if (e.confirm) {
                console.log(333)
              }
            }
          })
        } else {
          wx.showModal({
            content: prop.data.msg,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff5151',
            success(e) {
              if (e.confirm) {
                console.log(333)
              }
            }
          })
        }
      })
    }
  },
  //联系客服
  servicePhone(e) {
    if (e.currentTarget.dataset.tel) {
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.tel //仅为示例，并非真实的电话号码
      })
    } else {
      wx.showToast({
        title: '暂无联系方式',
        icon: "none"
      })
    }
  },
  // 取消订单
  cancelOrder(prop) {
    const that = this;
    wx.showModal({
      content: '是否取消该订单',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(e) {
        if (e.confirm) {
          let index = prop.currentTarget.dataset.index;
          if (that.data.listData[index].order_status_detail == "待支付") {
            let data = {
              token: wx.getStorageSync('token'),
              order_id_sn: that.data.listData[index].order_id + '=' + that.data.listData[index].master_order_sn
            }
            wx.showLoading({
              title: '加载中...',
            })
            myRequest.EasyHttp.post(api.reqUrls.cancelOrder, data).then(res => {
              wx.hideLoading();
              if (res.data.status == 1) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'success',
                  duration: 2000
                })
                setTimeout(() => {
                  that.getData();
                }, 2000)

              } else {
                wx.showModal({
                  content: res.data.msg,
                  showCancel: false,
                  confirmText: '确定',
                  confirmColor: '#ff5151',
                  success(e) {
                    if (e.confirm) {
                      console.log(333)
                    }
                  }
                })
              }
            }).catch(err => {
              wx.showModal({
                content: err.toString(),
                showCancel: false,
                confirmText: '确定',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {
                    console.log(333)
                  }
                }
              })
            })
          } else {
            wx.showActionSheet({
              itemList: that.data.reasons,
              success(res) {
                let data = {
                  token: wx.getStorageSync('token'),
                  order_id: that.data.listData[index].order_id,
                  consignee: that.data.listData[index].children[0].consignee,
                  mobile: that.data.listData[index].children[0].mobile,
                  user_note: that.data.reasons[res.tapIndex],
                  is_json: 1
                }
                wx.showLoading({
                  title: '加载中...',
                })
                myRequest.EasyHttp.post(api.reqUrls.cancelPaidOrder, data).then(res => {
                  wx.hideLoading();
                  if (res.data.status == 1) {
                    wx.showToast({
                      title: res.data.msg,
                      icon: 'success',
                      duration: 2000
                    })
                    setTimeout(() => {
                      that.getData();
                    }, 2000)
                  } else {
                    wx.showModal({
                      content: res.data.msg,
                      showCancel: false,
                      confirmText: '确定',
                      confirmColor: '#ff5151',
                      success(e) {
                        if (e.confirm) {
                          console.log(333)
                        }
                      }
                    })
                  }
                }).catch(err => {
                  wx.showModal({
                    content: err.toString(),
                    showCancel: false,
                    confirmText: '确定',
                    confirmColor: '#ff5151',
                    success(e) {
                      if (e.confirm) {
                        console.log(333)
                      }
                    }
                  })
                })
              },
              fail(res) {
                console.log(res.errMsg)
              }
            })
          }

        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    login.checkLogin().then(res => {
      that.getData()
    }).catch(err => {
      app.appCallBack = (e) => {
        that.getData()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const that = this;
    wx.showNavigationBarLoading()
    that.setData({
      page: 1,
      isEnd: true,
      isWithout: true,
    })
    that.getData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const that = this;
    if (!that.data.isEnd) {
      return
    }
    let page = that.data.page + 1
    let data = {
      token: wx.getStorageSync('token'),
      type: that.data.navData[that.data.navIndex].type,
      p: page
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getOrderList, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        if (res.data.result == null || res.data.result.length == 0) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
            duration: 1000
          })
          that.setData({
            isEnd: false
          })
        } else {
          that.setData({
            listData: [...that.data.listData, ...res.data.result],
            page: that.data.page + 1
          })
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})